<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="家长姓名" prop="parentName">
        <el-input v-model="queryParams.parentName" placeholder="请输入家长姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="关系" prop="relationship">
        <el-input v-model="queryParams.relationship" placeholder="请输入与学生的关系" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="职业" prop="parentJob">
        <el-input v-model="queryParams.parentJob" placeholder="请输入职业" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系方式" prop="parentPhone">
        <el-input v-model="queryParams.parentPhone" placeholder="请输入联系方式" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:parent:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:parent:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:parent:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:parent:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload multiple :action="uploadFileUrl" accept=".xlsx" :on-success="handleImport" :show-file-list="false" :headers="headers">
          <el-button type="warning" plain icon="el-icon-upload" size="mini">批量导入</el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-download" size="mini" @click="handleDownload">模板下载</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="parentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生名字" align="center" prop="studentId" width="120">
        <template slot-scope="scope">{{filterStudent(scope.row.studentId)}}</template>
      </el-table-column>
      <el-table-column label="家长姓名" align="center" prop="parentName"  width="120"/>
      <el-table-column label="关系" align="center" prop="relationship"  width="120"/>
      <el-table-column label="职业" align="center" prop="parentJob"  width="120"/>
      <el-table-column label="联系方式" align="center" prop="parentPhone"  width="150"/>
      <el-table-column label="住址" align="center" prop="parentAddress" />
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:parent:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:parent:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改家长对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学生名字" prop="studentId">
          <el-select style="width:100%" v-model="form.studentId" filterable remote reserve-keyword placeholder="学生名字" :remote-method="remoteMethod" :loading="studentLoad">
            <el-option v-for="item in options" :key="item.studentId" :label="item.studentName" :value="item.studentId">
              <span style="float: left">{{ item.studentName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.studentAge }}岁</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="与学生的关系" prop="relationship">
          <el-input v-model="form.relationship" placeholder="请输入与学生的关系" />
        </el-form-item>
        <el-form-item label="职业" prop="parentJob">
          <el-input v-model="form.parentJob" placeholder="请输入职业" />
        </el-form-item>
        <el-form-item label="联系方式" prop="parentPhone">
          <el-input v-model="form.parentPhone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="住址" prop="parentAddress">
          <el-input v-model="form.parentAddress" placeholder="请输入住址" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent } from "@/api/system/student";
import { listParent, getParent, delParent, addParent, updateParent } from "@/api/system/parent";
import axios from 'axios'
import { getToken } from "@/utils/auth";
export default {
  name: "Parent",
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 批量导入地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家长表格数据
      parentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        parentName: null,
        relationship: null,
        parentJob: null,
        parentPhone: null,
        parentAddress: null,
        status: null,
        isDelete: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      studentList: [],
      options: [],
      studentLoad: false
    };
  },
  created() {
    this.getList();
    this.listStudent()
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.studentLoad = true;
        this.options = this.studentList.filter(item => {
          return item.studentName.indexOf(query) > -1;
        });
      } else {
        this.options = JSON.parse(JSON.stringify(this.studentList));
      }
      this.studentLoad = true;
    },
    filterStudent(studentId) {
      const student = this.studentList.find(item => item.studentId === studentId)
      return student !== null && student !== undefined ? student.studentName : ""
    },
    /** 查询学生列表 */
    listStudent() {
      this.loading = true;
      listStudent({ pageNum: 1, pageSize: 10000 }).then(response => {
        this.studentList = response.rows;
        this.options = response.rows;
      });
    },
    /** 批量导入 */
    handleImport(res, file) {
      if (res.code === 200) {
        this.getList()
        this.$message.success("导入成功！")
      } else {
        this.$message.error(res.msg)
      }
    },
    /** 批量导入失败 */
    handleUploadError(err) {
      this.$modal.msgError("批量导入失败，请重试");
    },
    /** 模板下载 */
    async handleDownload() {
      try {
        const response = await axios.get('/部门模板.xlsx', { responseType: 'blob', });
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        const downloadLink = document.createElement('a');
        downloadLink.href = window.URL.createObjectURL(blob);
        downloadLink.download = '部门模板.xlsx';
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      } catch (error) {
        this.$message.error("模板下载失败，请联系管理员！")
      }
    },
    /** 查询家长列表 */
    getList() {
      this.loading = true;
      listParent(this.queryParams).then(response => {
        this.parentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pid: null,
        studentId: null,
        parentName: null,
        relationship: null,
        parentJob: null,
        parentPhone: null,
        parentAddress: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加家长";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pid = row.pid || this.ids
      getParent(pid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改家长信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pid != null) {
            updateParent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addParent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pids = row.pid || this.ids;
      this.$modal.confirm('是否确认删除家长编号为"' + pids + '"的数据项？').then(function () {
        return delParent(pids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/parent/export', {
        ...this.queryParams
      }, `parent_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
